package com.diipo.weibo;

import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.LinkedList;
import com.diipo.weibo.adapter.LetterItemAdapter;
import com.diipo.weibo.adapter.MsgItemAdapter;
import com.diipo.weibo.entity.Letter;
import com.diipo.weibo.utils.HttpUtils;
import com.diipo.weibo.utils.JsonUtils;
import com.google.gson.reflect.TypeToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class PrivateLetterActivity extends Activity{
	
	private String TAG = PrivateLetterActivity.class.getSimpleName();
	private ListView letterListView;
	private Button mbtnInbox;
	private Button mbtnsendBox;
	private Button mSend;
	private SharedPreferences mPrefs;
	private LinkedList<Letter> list2 = new LinkedList<Letter>();
	private Type listType = new TypeToken<LinkedList<Letter>>() {}.getType();
	private String mUrl_inbox = "/api/direct_messages/inbox.json?api_key="; //收件箱
	private String mUrl_sendbox = "/api/direct_messages/sent.json?api_key=";//发件箱
	private Context mctx;
	private boolean mboolInbox;
	private boolean mboolSendBox;
	private boolean mFlag;//switch the Inbox & SendBox btn
	
	private LinkedList<Letter> mInboxList = new LinkedList<Letter>();
	private LinkedList<Letter> mSendboxList = new LinkedList<Letter>();
	private Button mRefreshLetter;
	private TextView mMore;
	private String mId;   //for more letters recored
	//判断是否还有 更多 的信息
	private boolean inboxMore = true;
	private boolean sentMore = true;
	
	private Handler handler = new Handler();
	private LinearLayout mLinearLayout;
	private boolean mIsmore = false;
	private int moreCount = 0;
	TextView tv_no;
	private String mResponseCode = "0";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		// Hide title 
        requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView(R.layout.letter_view);
		mboolInbox = true;
		mboolSendBox = false;
		mFlag = false;
		
		mctx = this;
		mLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.list_footer, null);
		mMore = (TextView)mLinearLayout.findViewById(R.id.footer_more);
		mPrefs = getSharedPreferences(ConfigInfo.USER_PREFERENCES,MODE_PRIVATE);
		tv_no=(TextView)this.findViewById(R.id.tv_no);
		mRefreshLetter = (Button) findViewById(R.id.titlebar_refresh);
		mRefreshLetter.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mboolInbox){// add more inbox letters from the server
					Log.e(TAG, "get newest data inbox letter from the server pos = ");
//					mInboxList.clear();
					new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_inbox,"","","").execute();
				}else{
					Log.e(TAG, "get newest data sendbox letter from the server ");
//					mSendboxList.clear();
					new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_sendbox,"","","").execute();
				}
			}
		});
//		
		mMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mIsmore = true;
				if(mboolInbox){// add more inbox letters from the server
					try{
						mId = mInboxList.get(mInboxList.size()-1).getId();
					}catch(Exception e){
						Log.e(TAG, " Exception happend here,what's wrong?Baby?" );
						e.printStackTrace();
					}
					Log.e(TAG, " add more inbox letter from the server pos = " + mInboxList.size() + ",the last id = " + mId);
					new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_inbox,"","",mId).execute();
				}else{
					try{
						mId = mSendboxList.get(mSendboxList.size()-1).getId();
					}catch(Exception e){
						Log.e(TAG, " Exception happend here,what's wrong?Baby?" );
						e.printStackTrace();
					}
					Log.e(TAG, " add more sendbox letter from the server pos = " + mSendboxList.size() + ",the last id = " + mId);
					new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_sendbox,"","",mId).execute();
				}
			}
		});
		
		letterListView = (ListView) findViewById(R.id.letter_listview);
		letterListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Log.e(TAG, " PrivateLetterActivity onItemClick() called ...");
				Intent intent = new Intent(PrivateLetterActivity.this,WeiboDetailsActivity.class);
				if(mboolInbox){
					try{
						intent.putExtra(ConfigInfo.COMM.MSG_ID, mInboxList.get(position).getId());
					}catch(Exception e){
						Log.e(TAG, " Exception happend here,what's wrong?Baby?" );
						e.printStackTrace();
					}
				}else{
					try{
						intent.putExtra(ConfigInfo.COMM.MSG_ID, mSendboxList.get(position).getId());
					}catch(Exception e){
						Log.e(TAG, " Exception happend here,what's wrong?Baby?" );
						e.printStackTrace();
					}
				}
				intent.putExtra(ConfigInfo.COMM.ITEM_TYPE, "letter");  //私信
				startActivity(intent);
			}
			
		});
		
		letterListView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if(scrollState == SCROLL_STATE_FLING){
					mRefreshLetter.setEnabled(false);
				}else if(scrollState == SCROLL_STATE_IDLE){
//					handler.postDelayed(new Runnable() {
//						@Override
//						public void run() {
//							mRefreshLetter.setEnabled(true);
//						}
//					},2000);
					Log.e(TAG, " mRefreshWeibo.setEnabled(true).");
					mRefreshLetter.setEnabled(true);
				}else if(scrollState == SCROLL_STATE_TOUCH_SCROLL){
					mRefreshLetter.setEnabled(false);
				}else{
					
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
			}
		});
		
		mbtnInbox = (Button) findViewById(R.id.inbox_btn);
		mbtnsendBox = (Button) findViewById(R.id.sendbox_btn);
		mSend = (Button) findViewById(R.id.btn_title_reply);
		
		Log(TAG + "    ----     onCreate()");
		
		mbtnInbox.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e("pyb"," mbtnInbox Button was click");
				mboolInbox = true;
				mbtnInbox.setBackgroundResource(R.drawable.read_msg_selected);
				mbtnsendBox.setBackgroundResource(R.drawable.read_msg_normal);
				if(mboolInbox){
					mboolSendBox = false;
					LetterItemAdapter adapter = new LetterItemAdapter(mInboxList,PrivateLetterActivity.this);
					letterListView.setAdapter(adapter);
					if(!inboxMore){
						Log.e(TAG,"unreadMore:false==============nomore data");
						Log.i(TAG, " mMore.setVisibility(false).186");
						mMore.setVisibility(View.GONE);
					}else{
						if(mInboxList.size()< 20 || mSendboxList.size() < 20){
							mMore.setVisibility(View.GONE);
						}else{
						Log.i(TAG, " mMore.setVisibility(true).189");
						mMore.setVisibility(View.VISIBLE);
						}
					}
					return;
				}
				new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_inbox,"","","").execute();
				mFlag = false;
			}
		});
		
		mbtnsendBox.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e("pyb"," mbtnsendBox Button was click");
				mbtnInbox.setBackgroundResource(R.drawable.read_msg_normal);
				mbtnsendBox.setBackgroundResource(R.drawable.read_msg_selected);
				mboolSendBox = true;
				mboolInbox = false;
				if(mboolSendBox && mFlag){
					LetterItemAdapter adapter = new LetterItemAdapter(mSendboxList,PrivateLetterActivity.this);
					letterListView.setAdapter(adapter);
					if(!sentMore){
						Log.i(TAG, " mMore.setVisibility(false).213");
						mMore.setVisibility(View.GONE);
					}else{
						if(mInboxList.size()< 20 || mSendboxList.size() < 20){
							mMore.setVisibility(View.GONE);
						}else{
						Log.i(TAG, " mMore.setVisibility(true).216");
						mMore.setVisibility(View.VISIBLE);
						}
					}
					return;
				}
				new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_sendbox,"","","").execute();
				mFlag = true;
			}
		});
		
		mSend.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e("pyb"," mSend Button was click");
				Intent intent = new Intent(PrivateLetterActivity.this,CreateWeiBoActivity.class);
				intent.putExtra(ConfigInfo.COMM.SEND_TYPE, ConfigInfo.COMM.WEIBO_LETTER);
				startActivity(intent);
			}
		});
		letterListView.addFooterView(mLinearLayout);
		new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_inbox,"","","").execute();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log(TAG + "    ----     onResume()");
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log(TAG + " onStop()");
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log(TAG + " destory()");
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ConfirmExit();// 按了返回键，但已经不能返回，则执行退出确认
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void ConfirmExit() {// 退出确认
		AlertDialog.Builder dialog = new AlertDialog.Builder(PrivateLetterActivity.this);
		dialog.setTitle(mctx.getString(R.string.exit));
		dialog.setMessage(mctx.getString(R.string.is_exit_weibo));
		dialog.setPositiveButton(mctx.getString(R.string.btn_ok), new DialogInterface.OnClickListener() {// 退出按钮
					@Override
					public void onClick(DialogInterface dialog, int i) {
						// TODO Auto-generated method stub
						PrivateLetterActivity.this.finish();// 关闭activity
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				});
		dialog.setNegativeButton(mctx.getString(R.string.btn_cancle), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int i) {
				// 不退出不用执行任何操作
			}
		});
		dialog.show();// 显示对话框
	}
	
	void Log(String msg) {
		Log.e(TAG, "--" + msg);
	}
	
	/**
	 * 异步加载服务器上的微博数据的监听器,私信中的收件箱和发件箱
	 */
	private AsyncDataLoader.Callback asyncRemoteCallback = new AsyncDataLoader.Callback() {
		
		private String result;
		@Override
		public void onStart(String address,String id) {
//				mPrefs = getSharedPreferences(ConfigInfo.USER_PREFERENCES,MODE_PRIVATE);
				StringBuffer url = new StringBuffer();
				url.append(mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS,mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, ConfigInfo.COMM.CONST_SERVER_ADDRESS)));
				url.append(address);
				url.append(ConfigInfo.COMM.APY_KEY);
				
				if(mboolInbox){//收件箱
					if (mInboxList.size()>=20 && mIsmore) {
						url.append("&max_id=");
						url.append(id);
					}
				}else{
					if (mSendboxList.size()>=20 && mIsmore) {
						url.append("&max_id=");
						url.append(id);
					}
				}
				String username = mPrefs.getString(ConfigInfo.PREF_USERNAME,"");
				String passwd = mPrefs.getString(ConfigInfo.PREF_PASSWORD,"");
				
				//需要做出判断，username 或者 passwd为非法值
				
				result = HttpUtils.doPost(url.toString(), username,passwd, null);
				Log.e("","url address = "+url);
//				Log.e(""," username  = "+username);
//				Log.e(""," passwd  = "+passwd);
				Log.e(""," letter result =  " + result);
				if (result != ConfigInfo.HTTPRETURN.COMMHTTPERRORS 
						&& result != ConfigInfo.HTTPRETURN.HTTP_ERROR_400 
						&& result != ConfigInfo.HTTPRETURN.HTTP_ERROR_401 
						&& result != ConfigInfo.HTTPRETURN.HTTP_ERROR_CODE_404
						&& result != ConfigInfo.HTTPRETURN.HTTPERROR ) {
					if(mboolInbox){ //收件箱
						//大于20加载更多
						if (mInboxList.size()>=20 && mIsmore) {
							list2 = JsonUtils.parseUserFromJsons(result, listType);
							moreCount = list2.size();
							Iterator<Letter> iterator = list2.iterator();
							while (iterator.hasNext()) {
								mInboxList.add(iterator.next());
							}
							// hide the more btn data from the server
							if(list2.size() < 20){
								//hanlder在主线程做UI操作
								handler.post(new Runnable() {
									@Override
									public void run() {
										mMore.setVisibility(View.GONE);
//										mLinearLayout.setVisibility(View.GONE);
										Log.i(TAG, " mMore.setVisibility(false).346");
										inboxMore = false;
									}
								});
							}else{
								handler.postDelayed(new Runnable() {
									@Override
									public void run() {
										mMore.setVisibility(View.VISIBLE);
										Log.i(TAG, " mMore.setVisibility(true).355");
										inboxMore = true;
									}
								},1000);
							}
							//clear the list2 here
							list2.clear();
						}else {	
							mInboxList.clear();
							mInboxList = JsonUtils.parseUserFromJsons(result, listType);
							if(mInboxList.size()< 20){
								handler.post(new Runnable() {
									@Override
									public void run() {
										mMore.setVisibility(View.GONE);
//										mLinearLayout.setVisibility(View.GONE);
										Log.i(TAG, " mMore.setVisibility(false).361");
										inboxMore = false;
									}
								});
							}else{
								//mUnReadList.size() >= 20
								handler.postDelayed(new Runnable() {
									@Override
									public void run() {
										mMore.setVisibility(View.VISIBLE);
										Log.i(TAG, " mMore.setVisibility(true).380");
										inboxMore = true;
									}
								},1000);
							}
						}
					}else{//发件箱
						if (mSendboxList.size()>=20 && mIsmore) {
							list2 = JsonUtils.parseUserFromJsons(result, listType);
							moreCount = list2.size();
							Iterator<Letter> iterator = list2.iterator();
							while (iterator.hasNext()) {
								mSendboxList.add(iterator.next());
							}
							// hide the more btn data from the server
							if(list2.size() < 20){
								//hanlder在主线程做UI操作
								handler.post(new Runnable() {
									@Override
									public void run() {
										mMore.setVisibility(View.GONE);
//										mLinearLayout.setVisibility(View.GONE);
										Log.i(TAG, " mMore.setVisibility(false).390");
										sentMore = false;
									}
								});
							}else{
								handler.postDelayed(new Runnable() {
									@Override
									public void run() {
										mMore.setVisibility(View.VISIBLE);
										Log.i(TAG, " mMore.setVisibility(true).411");
										sentMore = true;
									}
								},1000);
							}
							//clear the list2 here
							list2.clear();
						}else {	
							mSendboxList.clear();
							mSendboxList = JsonUtils.parseUserFromJsons(result, listType);
							if(mSendboxList.size()< 20){
								handler.post(new Runnable() {
									@Override
									public void run() {
										mMore.setVisibility(View.GONE);
//										mLinearLayout.setVisibility(View.GONE);
										Log.i(TAG, " mMore.setVisibility(false).405");
										sentMore = false;
									}
								});
							}else{
								//mUnReadList.size() >= 20
								handler.postDelayed(new Runnable() {
									@Override
									public void run() {
										mMore.setVisibility(View.VISIBLE);
										Log.i(TAG, " mMore.setVisibility(true).435");
										sentMore = true;
									}
								},1000);
							}
						}
					}
				}else if(result == ConfigInfo.HTTPRETURN.HTTP_ERROR_CODE_404){
					Log.e(TAG, " no data:404===========================================  421");
					mResponseCode = "404";
					//mMore.setVisibility(View.GONE);
					handler.post(new Runnable() {
						@Override
						public void run() {
							mMore.setVisibility(View.GONE);
							Log.i(TAG, " mMore.setVisibility(false).427");
						}
					});
					if(mboolInbox)
						inboxMore = false;
					else
						sentMore = false;
				}
		}

		@Override
		public void onFinish() {
			
			/*if(!letterListView.isFocusable()){
				Toast.makeText(PrivateLetterActivity.this, ConfigInfo.HTTPRETURN.HTTPERROR, Toast.LENGTH_LONG).show();
				return;
			}*/
			LetterItemAdapter adapter = null;
			if (result == ConfigInfo.HTTPRETURN.COMMHTTPERRORS
					|| result == ConfigInfo.HTTPRETURN.HTTP_ERROR_400
					|| result == ConfigInfo.HTTPRETURN.HTTP_ERROR_401
					|| result == ConfigInfo.HTTPRETURN.HTTPERROR
					|| result == ConfigInfo.HTTPRETURN.HTTP_ERROR_CODE_404){
				Toast.makeText(PrivateLetterActivity.this, 
						result.equals("404")?mctx.getString(R.string.no_send_letter):result, Toast.LENGTH_LONG).show();
//				Toast.makeText(PrivateLetterActivity.this, result, Toast.LENGTH_LONG).show();
				if(mInboxList.size()< 20 || mSendboxList.size() < 20){
					mMore.setVisibility(View.GONE);
				}
				
				if(mboolInbox){
					if(result.equals("404")){//在web端将数据删除了
						mInboxList.clear();
					}
					if(mInboxList.size()<=0){
						tv_no.setVisibility(View.VISIBLE);
						tv_no.setText("没有收到的私信。");
					}
					adapter = new LetterItemAdapter(mInboxList,PrivateLetterActivity.this);
					letterListView.setAdapter(adapter);
					
				}else{
					if(result.equals("404")){  //在web端将数据删除了
						mSendboxList.clear();
					}
					if(mSendboxList.size()<=0){
						tv_no.setVisibility(View.VISIBLE);
						tv_no.setText("没有发出去的私信。");
					}
					adapter = new LetterItemAdapter(mSendboxList,PrivateLetterActivity.this);
					letterListView.setAdapter(adapter);
				}
				return;
			}
			
			if(mboolInbox){
				if(mInboxList.size() < 20 && mInboxList.size() > 1){
					mMore.setVisibility(View.GONE);
					Log.i(TAG, " mMore.setVisibility(false).444");
					inboxMore = false;
				}
				if(mInboxList.size() < 1){
					Log.e(TAG, " no data===========================================  ");
					Toast.makeText(PrivateLetterActivity.this, mResponseCode.equals("404")?mctx.getString(R.string.inbox_empty):ConfigInfo.HTTPRETURN.HTTPERROR, Toast.LENGTH_LONG).show();
					//return;
				}
				adapter = new LetterItemAdapter(mInboxList,PrivateLetterActivity.this);
				letterListView.setAdapter(adapter);
				if(mInboxList.size()<=0){
					tv_no.setVisibility(View.VISIBLE);
					tv_no.setText("没有收到的私信。");
				}
				if(mIsmore){
					letterListView.setSelection(mInboxList.size()-1-moreCount);
					Log.e(TAG, " +++++ ===================mInboxList.size() = "+ mInboxList.size());
					mIsmore = false;
				}
			}else{
				if(mSendboxList.size() < 20){
					mMore.setVisibility(View.GONE);
					Log.i(TAG, " mMore.setVisibility(false).463");
					sentMore = false;
				}
				if(mSendboxList.size() < 1){
					Log.e(TAG, " no data===========================================  ");
					Toast.makeText(PrivateLetterActivity.this, mResponseCode.equals("404")?mctx.getString(R.string.outbox_empty):ConfigInfo.HTTPRETURN.HTTPERROR, Toast.LENGTH_LONG).show();
					//return;
				}
				adapter = new LetterItemAdapter(mSendboxList,PrivateLetterActivity.this);
				letterListView.setAdapter(adapter);
				if(mSendboxList.size()<=0){
					tv_no.setVisibility(View.VISIBLE);
					tv_no.setText("没有发出去的私信。");
				}
				if(mIsmore){
					letterListView.setSelection(mSendboxList.size()-1-moreCount);
					Log.e(TAG, " ===================mSendboxList = "+ mSendboxList.size());
					mIsmore = false;
				}
			}
		}

		@Override
		public void onPrepare() {
		}
		@Override
		public void onStart(String address, String arg1, String arg2) {
			// TODO Auto-generated method stub
			
		}
	};
}
